package com.mit.wx.listener;

import com.alibaba.fastjson.JSON;
import com.mit.wx.conf.WeixinConfiguration;
import com.mit.wx.entity.AccessToken;
import com.mit.wx.service.AccessTokenService;
import com.mit.wx.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author 郭文梁
 * <p>${DATE} ${TIME} Create by 郭文梁</p>
 * <p>FOR: </p>
 */
@Component
@Slf4j
public class TokenSchedulingListener implements ApplicationRunner, ThreadFactory, Runnable {
    private static final String ACCESS_TOKEN_API_TEMPLATE = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static final double TOKEN_RESET_TIME_RATIO = 0.8;
    private ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, this);

    private final AccessTokenService accessTokenStore;
    private final WeixinConfiguration weixinConfiguration;

    @Autowired
    public TokenSchedulingListener(AccessTokenService accessTokenStore, WeixinConfiguration weixinConfiguration) {
        this.accessTokenStore = accessTokenStore;
        this.weixinConfiguration = weixinConfiguration;
    }


    private void startFirstScheduled() {
        executorService.execute(this);
    }

    @Override
    public void run() {
        log.info("Obtain access token......");
        try {
            String resp = getAccessToken();
            AccessToken accessToken = JSON.parseObject(resp, AccessToken.class);
            accessTokenStore.setAccessToken(accessToken);
            if (accessToken.getExpiresIn() <= 0) {
                log.error("could not refresh access token,server response={}", resp);
                throw new RuntimeException("could not refresh access token");
            }
            executorService.schedule(this, (long) (accessToken.getExpiresIn() * TOKEN_RESET_TIME_RATIO), TimeUnit.SECONDS);
            log.info("Access token refreshed {}", accessToken);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getAccessToken() throws IOException {
        String url = String.format(ACCESS_TOKEN_API_TEMPLATE, weixinConfiguration.getAppID(), weixinConfiguration.getAppSecret());
        return HttpUtil.get(url);
    }

    @Override
    public void run(ApplicationArguments args) {
        log.info("Start a scheduling for obtain access token");
        startFirstScheduled();
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setName("Obtain access token Thread");
        return thread;
    }
}
